package order;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oims.OrderRecordItem;
import sims.StockRecord;
import cims.CustomerRecord;

public class OrderEntryServlet extends HttpServlet {

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	/* (非 Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		perform(req, resp);
	}

	private void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String msg = null;

		req.setCharacterEncoding("UTF-8");

		String customer = req.getParameter("customer");
		CustomerRecord crec = new CustomerRecord();
		Map<String, String> map = crec.getInfo(customer);
		req.setAttribute("customer", new Customer(map));

		Order order = new Order();
		order.setCustomer(customer);
		order.setDate(new Timestamp((new Date()).getTime()));

		ArrayList<OrderRecordItem> items = new ArrayList<OrderRecordItem>();
		for (int i=0 ; i<6 ; i++) {
			String number = req.getParameter("number" + i);
			if (number != null && number.length() > 0) {
				String strPrice = req.getParameter("price" + i);
				String strQuantity = req.getParameter("quantity" + i);

				OrderItem item = OrderItem.validate(number, strPrice, strQuantity);
				if (item == null) {
					msg = "注文情報の入力に誤りがあります。";
					break;
				}

				StockRecord srec = new StockRecord();
				int stock = srec.getInfo(number);
				if (stock < item.getQuantity()) {
					msg = "在庫が不足しています。";
					break;
				}

				OrderRecordItem orderItem = new OrderRecordItem();
				orderItem.setProduct(item.getProduct());
				orderItem.setPrice(item.getPrice());
				orderItem.setQuantity(item.getQuantity());

				items.add(orderItem);
			}
		}

		String path = null;
		HttpSession session = req.getSession();
		session.setAttribute("order", order);
		session.setAttribute("items", items);

		if (msg != null) {
			req.setAttribute("msg", msg);
			path = "/order/order_edit.jsp";
		}
		else {
			path = "/order/order_check.jsp";
		}

		RequestDispatcher disp = req.getRequestDispatcher(path);
		disp.forward(req, resp);
	}
}
